package com.example.app_mqttclient.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.example.app_mqttclient.MainActivity;
import com.example.app_mqttclient.activity.BlockToysActivity;
import com.example.app_mqttclient.obj.DataAnalyse;
import com.example.app_mqttclient.obj.DeviceView;
import com.example.app_mqttclient.obj.HealthData;

public class MyBroadcast extends BroadcastReceiver {

    private static final String mqttRecvDataAction = "com.example.app_mqttclient.MQTT_RECV_DATA";
    private static final String TAG = "MyBroadcast";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equals(mqttRecvDataAction))
        {
            int index = intent.getIntExtra("deviceIndex", 0);
            String msg = intent.getStringExtra("msg");
            Log.i(TAG, "device index: " + index + ", msg: " + msg);
            switch(DataAnalyse.stringFirstKey(msg, ":"))
            {
                case "LINK":
                    boolean linkState = DataAnalyse.stringFindKeyword(msg, ",", "LINK", "online");
                    // 改变某个deviceView的属性
                    DeviceView deviceView = null;
                    deviceView = MainActivity.deviceData.get(index);
                    deviceView.setDeviceState(linkState);
                    MainActivity.deviceData.set(index, deviceView);
                    MainActivity.deviceAdapter.notifyDataSetChanged(); // 通知改变
                    break;
                case "RATE":
                    HealthData healthData = new HealthData();
                    String str = null;
                    str = DataAnalyse.stringReturnValue(msg, ",", "RATE");
                    healthData.setHeartRate(str);
                    str = DataAnalyse.stringReturnValue(msg, ",", "SPO");
                    healthData.setSpo(str);
                    str = DataAnalyse.stringReturnValue(msg, ",", "BK");
                    healthData.setBk(str);
                    str = DataAnalyse.stringReturnValue(msg, ",", "HIGH");
                    healthData.setHighYa(str);
                    str = DataAnalyse.stringReturnValue(msg, ",", "LOW");
                    healthData.setLowYa(str);
                    BlockToysActivity.myHealthData = healthData;
                    break;

            }
        }
    }
}
